package com.hoshiicloud.user.service.impl.usercenter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.user.dto.userCenter.MemberDto;
import com.hoshiicloud.user.entity.company.Company;
import com.hoshiicloud.user.entity.company.Member;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.entity.usercenter.PlatConsumer;
import com.hoshiicloud.user.mapper.usercenter.PlatConsumerMapper;
import com.hoshiicloud.user.param.PlatStoreConsumerPageParam;
import com.hoshiicloud.user.service.company.ICompanyService;
import com.hoshiicloud.user.service.rbac.IMemberService;
import com.hoshiicloud.user.service.usercenter.IPlatConsumerService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 平台消费者信息Service接口实现类
 *
 * @author : yangcheng
 * @date : 2019/5/9 14:44
 * @mail : maiboyc@163.com
 **/
@Service
public class PlatConsumerServiceImpl extends ServiceImpl<PlatConsumerMapper, PlatConsumer> implements IPlatConsumerService {

    // id生成Service
    @Autowired
    private IdGeneratorService idGeneratorService;


    @Autowired
    private IMemberService memberService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private PlatConsumerMapper platConsumerMapper;

    /**
     * 根据id获取
     *
     * @param id ID
     * @return PlatConsumer
     */
    @Cacheable(cacheNames = "platConsumer", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "用户管理-用户基本信息管理-根据ID查询用户基本信息")
    @Override
    public PlatConsumer getById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 根据一组id
     *
     * @param ids id组
     * @return List<PlatConsumer>
     */
    @Cacheable(cacheNames = "platConsumer", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#ids")
    @Logable(authName = "用户管理-用户基本信息管理-根据ID组查询用户基本信息")
    @Override
    public List<PlatConsumer> getByIds(List<Long> ids) {
        return baseMapper.selectBatchIds(ids);
    }

    /**
     * 保存
     *
     * @param entity 实体对象
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "platConsumer", allEntries = true)
    @Logable(authName = "用户管理-用户基本信息管理-新增用户基本信息")
    @Override
    public Long insert(PlatConsumer entity) throws ServiceException {
        // 调用主键生成微服务生成主键
        String id = idGeneratorService.queryGeneratorId();
        if (id == null) {
            throw new ServiceException(CommonError.error("新增用户基本信息失败,生成ID主键失败"));
        }

        Member member = memberService.getById(entity.getMemberId());
        if (null == member) {
            throw new ServiceException(CommonError.error("新增用户基本信息失败，没有查询到对应的租户会员信息"));
        }
        Company company = companyService.getById(entity.getCompanyId());
        if (null == company) {
            throw new ServiceException(CommonError.error("新增用户基本信息失败，没有查询到对应的租户信息"));
        }
        // 调用平台微服务检查平台信息是否存在
        // Platform platform = platformService.getById(entity.getPlatformid());
//        if ( null == platform ) {
//            throw new ServiceException(CommonError.error("新增用户基本信息失败，没有查询到对应的平台信息"));
//        }
        //TODO 推荐人可以为空，如果不为空调用第三方服务验证所属机构ID和推荐人ID,暂时还没弄清楚推荐人机构哪里来

        // 专属二维码(图片服务器不能用，这里存个假的)
        entity.setQrCode("http://www.google.com/XXX.jpg");
        // 推荐码
        entity.setInviteCode(getUniqueInviteCode(idGeneratorService.getPlatCousomerCode()));
        // 会员等级
        entity.setLevelId(1);
        // 变更时间
        entity.setLevelTime(LocalDateTime.now());
        // 系统token
        entity.setSysToken("T93328432143214321");
        // 推送token
        entity.setPushToken("T93328432143214322");
        // 设备token
        entity.setDeviceToken("T93328432143214323");
        // 自动生成id，创建日期 修改日期 创建人 修改人 删除标识
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setCreatedBy("admin");// 需要拿当前的登录人
        entity.setUpdatedBy("admin");// 需要拿当前的登录人
        entity.setDeleted(0);
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增用户基本信息失败"));
        }
        return entity.getId();
    }

    /**
     * 修改
     *
     * @param entity 实体对象
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "platConsumer", allEntries = true)
    @Logable(authName = "用户管理-用户基本信息管理-修改用户基本信息")
    @Override
    public Long update(PlatConsumer entity) throws ServiceException {
        // 自动填入修改时间 修改人
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setUpdatedBy("admin1");// 需要拿当前的登录人
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改用户基本信息失败"));
        }
        return entity.getId();
    }

    /**
     * 查询
     *
     * @param entity 查询参数实体
     * @return IPage<PlatConsumer>
     */
    @Cacheable(cacheNames = "platConsumer", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#entity.pageIndex+':'+#entity.pageSize+':'+#entity.nickname+':'+#entity.name+':'+#entity.idCard+':'+#entity.address+':'+#entity.telephone+':'+#entity.inviteCode+':'+#entity.sex+':'+#entity.email+':'+#entity.regShare+':'+#entity.channel")
    @Logable(authName = "用户管理-用户基本信息管理-分页查询用户基本信息")
    @Override
    public IPage<PlatConsumer> List(PlatConsumer entity) {
        QueryWrapper<PlatConsumer> queryWrapper = new QueryWrapper();
        IPage<PlatConsumer> page = new Page();
        if (entity.getPageIndex() != null) {
            page.setCurrent(entity.getPageIndex());
        }
        if (entity.getPageSize() != null) {
            page.setSize(entity.getPageSize());
        }
        if (StringUtils.isNotEmpty(entity.getInviteCode())) {
            queryWrapper.eq("inviteCode", entity.getInviteCode());
        }
        if (entity.getRegShare() != null) {
            queryWrapper.eq("reg_share", entity.getRegShare());
        }
        if (entity.getChannel() != null) {
            queryWrapper.eq("channel", entity.getChannel());
        }
        // 默认查询只查询未逻辑删除的数据
        queryWrapper.eq("deleted", 0);
        return baseMapper.selectPage(page, queryWrapper);
    }

    /**
     * 根据参数查询平台消费者信息
     *
     * @param entity 查询参数
     * @return List<PlatConsumer>
     */
    @Cacheable(cacheNames = "platConsumer", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#entity.inviteCode+':'+#entity.regShare+':'+#entity.channel")
    @Logable(authName = "用户管理-用户基本信息管理-根据参数查询平台消费者信息")
    @Override
    public List<PlatConsumer> getConsumers(PlatConsumer entity) {
        QueryWrapper<PlatConsumer> queryWrapper = new QueryWrapper();
        if (StringUtils.isNotEmpty(entity.getInviteCode())) {
            queryWrapper.eq("invite_code", entity.getInviteCode());
        }
        if (null != entity.getRegShare()) {
            queryWrapper.eq("reg_share", entity.getRegShare());
        }
        if (null != entity.getChannel()) {
            queryWrapper.eq("channel", entity.getChannel());
        }
        // 默认查询只查询未逻辑删除的数据
        queryWrapper.eq("deleted", 0);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 删除
     *
     * @param id ID
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "platConsumer", allEntries = true)
    @Logable(authName = "用户管理-用户基本信息管理-删除用户基本信息")
    @Override
    public boolean delete(Long id) {
        PlatConsumer platConsumer = this.getById(id);
        platConsumer.setDeleted(1);
        int row = baseMapper.updateById(platConsumer);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除用户基本信息失败"));
        } else {
            return true;
        }
    }

    private String getUniqueInviteCode(String inviteCode) throws ServiceException {
        String result = "";
        if (StringUtils.isNotEmpty(inviteCode)) {
            // 检查当前生成的userCode是否已经存在
            PlatConsumer c = new PlatConsumer();
            c.setInviteCode(inviteCode);
            List<PlatConsumer> consumers = getConsumers(c);
            if (consumers.size() > 0) {
                getUniqueInviteCode(idGeneratorService.getPlatCousomerCode());
            } else {
                result = inviteCode;
            }
        } else {
            throw new ServiceException(CommonError.error("新增租户会员失败,生成会员编号失败"));
        }
        return result;
    }

    @Override
    //@Cacheable(cacheNames = "platConsumer", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#param.toString()")
    @Logable(authName = "用户管理-用户基本信息管理-分页查询店铺消费者列表")
    public Page<MemberDto> getStoreConsumerPage(PlatStoreConsumerPageParam param) {
        IPage<MemberDto> page=new Page<>();
        page.setSize(param.getPageSize());
        page.setCurrent(param.getPageIndex());
        return platConsumerMapper.storeConsumersPageList(page,param);
    }
}
